const { prisma } = require('../config/prisma');

/**
 * 获取支付状态
 */
const getPaymentStatus = async (req, res) => {
  try {
    const { orderNo } = req.params;

    // 查询订单
    const order = await prisma.order.findFirst({
      where: {
        orderNo,
        userId: req.user.id
      },
      select: {
        id: true,
        orderNo: true,
        status: true,
        payTime: true,
        amount: true,
        memberType: true,
        days: true
      }
    });

    if (!order) {
      return res.status(404).json({
        code: 404,
        message: '订单不存在'
      });
    }

    res.status(200).json({
      code: 200,
      data: {
        orderNo: order.orderNo,
        status: order.status,
        payTime: order.payTime,
        amount: Number(order.amount),
        memberType: order.memberType,
        days: order.days
      }
    });
  } catch (error) {
    console.error('Get payment status error:', error);
    res.status(500).json({
      code: 500,
      message: '查询支付状态失败'
    });
  }
};

/**
 * 处理支付回调通知
 */
const handlePaymentNotify = async (req, res) => {
  try {
    const { resource } = req.body;
    
    if (!resource || !resource.out_trade_no) {
      console.error('Missing order number in payment notification');
      return res.json({
        code: 'SUCCESS'
      });
    }

    const orderNo = resource.out_trade_no;
    const order = await prisma.order.findFirst({
      where: { orderNo }
    });

    if (!order || order.status !== 0) {
      console.log('Order not found or already processed:', orderNo);
      return res.json({
        code: 'SUCCESS'
      });
    }

    // 开启事务处理
    await prisma.$transaction(async (prisma) => {
      // 更新订单状态
      await prisma.order.update({
        where: { id: order.id },
        data: {
          status: 1,
          payTime: new Date(resource.success_time)
        }
      });

      // 更新用户会员信息
      const user = await prisma.user.findUnique({
        where: { id: order.userId }
      });

      const now = new Date();
      let expireTime;
      if (user.memberType > 0 && user.expireTime > now) {
        // 如果是已有会员，在当前到期时间基础上增加天数
        expireTime = new Date(user.expireTime.getTime() + order.days * 24 * 60 * 60 * 1000);
      } else {
        // 如果不是会员，从当前时间开始计算
        expireTime = new Date(now.getTime() + order.days * 24 * 60 * 60 * 1000);
      }

      await prisma.user.update({
        where: { id: order.userId },
        data: {
          memberType: order.memberType,
          expireTime
        }
      });
    });

    res.json({
      code: 'SUCCESS'
    });
  } catch (error) {
    console.error('Payment notify error:', error);
    res.json({
      code: 'SUCCESS'
    });
  }
};

module.exports = {
  getPaymentStatus,
  handlePaymentNotify
}; 